<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Testpaper;

use Exception;

use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
/**
 * 题库管理
 *
 * @icon fa fa-circle-o
 */
class Questions extends Backend
{

    /**
     * Questions模型对象
     * @var \app\admin\model\Questions
     */
    protected $model = null;

    // protected $dataLimit = true;
    protected $dataLimit = 'auth';
    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = ["status","remark"];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Questions;
        $this->view->assign("typedataList", $this->model->getTypedataList());
        $this->view->assign("diffdataList", $this->model->getDiffdataList());
        $this->view->assign("statusList", $this->model->getStatusList());

        $this->assignconfig('can_change_status',$this->auth->check('questions/change_status'));
        $this->assignconfig('admin_id',$this->auth->id);
        $this->assignconfig('admin_ids',$this->auth->getChildrenAdminIds(true));
        $this->CourseModel = model('Course');
        $bank = $this->CourseModel->order('index_link asc')->select();
        $bankList = [];
        foreach ($bank as $value) {
            if($value['pid'] == 0){
                $bankList[$value['id']] = $value['name'];
            }else{
                $bankList[$value['id']] = '____' . $value['name'];
            }
        }
        $this->view->assign([
            'bankList' => $bankList,
        ]);
    }
  
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        // 如果是审核组的
        if($this->auth->check('questions/change_status')){
            $this->dataLimit = false;
        }
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['course'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('course')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 题目列表
     */
    public function list()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['course'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('course')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 题目是否被占用
     *
     * @param [type] $ids
     * @return bool
     */
    public function is_useing($ids = null)
    {
        $ids = $ids?:$this->request->post('ids');
        if(empty($ids)){
            $this->error('请先选择要删除的题目');
        }

        //   判断是否被占用

        $idsArray = explode(',',$ids);
        $testpaperModel = new Testpaper;
        $useing = [];
        foreach ($idsArray as $key => $id) {
           if( $testpaperModel->where('questions','like','%"id":'.$id.',%')->find() ){
            // 被占用了
            $useing[] = $id;
           }
        }

        if(empty($useing)){
            $this->success('未被占用',null,["ids"=>$ids]);
        }
        else{
            $this->error("问题 ".implode(',',$useing)." 被占用了，确定要删除吗？",null,["ids"=>$ids]);
        }

    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            $testpaperModel = new Testpaper;
            foreach ($list as $item) {
                $count += $item->delete();
                // 删除试卷内的题目
                $testpaperModel->delQuestion($item->id);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    

    /**
     * 审核
     *
     * @return void
     */
    public function change_status($type="pass",$id=null)
    {
        if(is_null($id)){
            $this->error('缺少id参数');
        }
        $where=[];
        if(is_array($id)){
            $where['id'] = ['in',$id];
        }
        else{
            $where['id'] = $id;
        }
        if($type == 'pass'){
            // 审核通过
            $res = $this->model->where($where)->update(['status' => 3]);
        }
        else{
            // 拒绝
            $remark = $this->request->post('remark');
            if(empty($remark)){
                $this->error('请先填写拒绝原因');
            }
            $res = $this->model->where($where)->update(['status' => 2,'remark'=>$remark]);
        }

        if($res){
            $this->success('审核完成');
        }
        else{
            $this->error('审核异常');
        }
    }

    public function getlist_by_ids()
    {
      $ids = input('ids/a',[]);
      $lists = [];
      foreach ($ids as $type => $idArray) {
        $lists[$type] = $this->model->where('id','in',$idArray)->select();
      }
      $this->success('ok',null,$lists);
    }

    // public function import($data=null){
    //     var_dump($data);exit;

    //     return parent::import();
    // }

    public function import($data = null)
    {
        // 如果没有传入数据，则尝试从请求中获取
        if (empty($data)) {
            $data = $this->request->post();
        }
        // var_dump($this->request->file());exit;
        // 检查是否有文件上传
        if ($this->request->isPost() && isset($data['file']) && file_exists(ROOT_PATH . 'public' . DS . $data['file'])) {
            
            $filePath = ROOT_PATH . 'public' . DS . $data['file']; // 获取文件的临时路径
            $ext = pathinfo($filePath, PATHINFO_EXTENSION); // 获取文件扩展名

            // 根据文件类型选择解析器
            if ($ext === 'csv') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
            } elseif ($ext === 'xls') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
            } elseif ($ext === 'xlsx') {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            } else {
                $this->error('文件后缀不是excel文档支持的格式');
            }

            
            // 加载文件
            try {
                $spreadsheet = $reader->load($filePath);

                
                $sheet = $spreadsheet->getActiveSheet();
                $allRow = $sheet->getHighestRow(); // 获取总行数
                $allColumn = $sheet->getHighestColumn(); // 获取总列数
                $allColumnNumber = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($allColumn);

                // 读取表头
                $fields = [];
                for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $allColumnNumber; $currentColumn++) {
                        $val = $sheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }
                
                // 读取数据
                $insert = [];
                for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $allColumnNumber; $currentColumn++) {
                        $val = $sheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = array_combine($fields, $values); // 将表头与数据结合
                    $insert[] = $row;
                }
                // 特殊处理
                foreach ($insert as &$item) {
                    // 对每个字段进行特殊处理
                    if (isset($item['typedata'])) {
                        // 示例：截断字段长度
                        $item['typedata'] = strval($item['typedata']);
                    }
                    $item["createtime"] = time();
                    $item["updatetime"] = time();
                    $item["status"] = '1';
                    $item["admin_id"] = $this->auth->id;
                }
                // var_dump($insert);exit;
                // 插入数据库
                if ($insert) {
                    $this->model->saveAll($insert);
                    $this->success('题目添加成功', null, ['count' => count($insert)]);
                    exit;
                } else {
                    $this->error('题目添加失败');
                    exit;
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
                exit;
            }
        } else {
            $this->error('上传文件失败');
            exit;
        }
    }

    /**
     * ai添加题目
     *
     * @return void
     */
    public function addai()
    {
        if($this->request->isAjax()){
            $params = $this->request->param('row/a');
            if(empty($params["questions"])){
                $this->error('请先生成题目');
            }
            $questions = json_decode($params["questions"],true);

            $saveData = [];
            foreach ($questions as $key => $value) {
                $answers = json_encode($value["answer"], JSON_UNESCAPED_UNICODE);
                $saveData[] = [
                    "course_id"=>$params["course_id"],
                    "typedata"=> $params["typedata"],
                    "title"=> $value["question"],
                    "optionjson"=>json_encode($value["options"],JSON_UNESCAPED_UNICODE),
                    "answers"=> $answers,
                    "answerscontent"=>$value["jiexi"],
                    "diffdata"=> $params["diffdata"],
                    "createtime"=>time(),
                    "updatetime"=>time(),
                    "status"=>1,
                    "admin_id"=>$this->auth->id,
                ];
            }

            $res = Db::name('questions')->insertAll($saveData);
            if($res){

                $this->success('保存成功',null, $saveData);
            }
            else{
                $this->error('保存失败');
            }
        }
        return $this->view->fetch();
    }

    /**
     * 审核
     *
     * @return void
     */
    public function eventai()
    {
        // 设置SSE响应头
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
        header('X-Accel-Buffering: no'); // 禁用Nginx缓存
        ignore_user_abort(true);
        set_time_limit(0);

        // 获取请求参数
        $params = $this->request->param('row/a');

        $response_format = 'text';
        if($params["pingtai"] == 'deepseek'){
            $apiUrl = 'https://api.deepseek.com/chat/completions';
            $apiToken = config('ds.deepseek');
            if($params["model"] == 'v3'){
                $model = "deepseek-chat";
            }
            else{
                $model = "deepseek-reasoner";
            }
        }
        else{

            $apiUrl = 'https://api.siliconflow.cn/v1/chat/completions';
            $apiToken = config('ds.siliconflow');

            if ($params["model"] == 'v3') {
                $model = "deepseek-ai/DeepSeek-V3";
            } else {
                $model = "deepseek-ai/DeepSeek-R1";
            }
        }

        $courseName = Db::name("course")->where('id',$params["course_id"])->value('name');


        $prompt = $params["prompt"]."，科目为：". $courseName;

        if($params["typedata"] == '1'){
            $prompt .= "，要求是单项选择题，并且带着选项，答案应该是所在选项数组的索引值";
        } else if ($params["typedata"] == '2') {
            $prompt .= "，要求是多项选择题，并且带着选项，如果答案有多个时放在数组里，答案应该是所在选项数组的索引值";
        } else if ($params["typedata"] == '3') {
            $prompt .= "，要求是判断题，并且带着选项，选项为对或错，答案应该是所在选项数组的索引值";
        } else if ($params["typedata"] == '4') {
            $prompt .= "，要求是填空题，可以有多个空，不需要选项，选项留空数组即可";
        } else if ($params["typedata"] == '5') {
            $prompt .= "，要求是问答题，不需要选项，选项留空数组即可";
        }

        $rule = '[{"question":"<中文问题的题目>","options":["选项1","选项2","选项3","选项4"],"answer":["<正确答案>"],"jiexi":"<题目的解析>"}]';
        $data = [
            "model" => $model,
            "messages" => [
                [
                    "role" => "system",
                    "content" => "你是一个json生成器，仅返回一个标准的json格式，不要markdown和其他内容，不要说任何话，只返回json格式"
                ],
                [
                    "role" => "user",
                    "content" => $prompt."，还有答案和解析，生成的格式是一个json格式，不要markdown:$rule"
                ]
            ],
            "stream" => true,
            "max_tokens" => 1024,
            "temperature" => 0.7,
            "response_format"=>[
                "type"=> $response_format
            ]
        ];

        // trace($data,'deepseek-api');

        $ch = curl_init($apiUrl);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $apiToken,
                'Content-Type: application/json',
                'Accept: text/event-stream'
            ],
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_WRITEFUNCTION => function ($ch, $data) {
                
                // 处理每个数据块
                foreach (explode("\n", $data) as $line) {
                    if (strpos($line, 'data: ') === 0) {
                        $json = substr($line, 6);
                        if ($json === '[DONE]') {
                            echo "event: done\n";
                            echo "data: \n\n";
                            ob_flush();
                            flush();
                            return strlen($data);
                        }

                        // echo "data: " .$json;
                        // ob_flush();
                        // flush();

                        $response = json_decode($json, true);
                        if (isset($response['choices'][0]['delta']['content'])) {
                            echo "data: " . json_encode([
                                'content' => $response['choices'][0]['delta']['content'],
                                'reasoning_content' => null,
                            ]) . "\n\n";
                        } else if (isset($response['choices'][0]['delta']['reasoning_content'])) {
                            echo "data: " . json_encode([
                                'content' => null,
                                'reasoning_content' => $response['choices'][0]['delta']['reasoning_content'],
                            ]) . "\n\n";
                        }
                        ob_flush();
                        flush();
                    }
                }
                return strlen($data);
            }
        ]);

        // 执行请求
        $response = curl_exec($ch);

        // 错误处理
        if (curl_errno($ch)) {
            echo "event: error\n";
            echo "data: " . json_encode(['error' => curl_error($ch)]) . "\n\n";
        } else {
            // 发送结束标记
            echo "event: end\n";
            echo "data: \n\n";
        }

        ob_flush();
        flush();
        curl_close($ch);
        exit;
    }

}
